// 系统设置
import { FC, useEffect, useState, useRef } from 'react'
import { Tabs, Form, Input, Button, Upload, message, QRCode, Table, Switch } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import img2 from '../../component/images/QRcide.jpg'
import { settinglist, settingedit, field, changestatus, addxiu } from "../../api/system"; //接口
import "../../css/system.scss";


const system: FC = () => {

  //tab切换 
  const { TabPane } = Tabs;
  const onChange = (key: string) => {
  };


  // 网站设置的数据
  const setin: any = useRef()

  let getsettinglist = async () => {
    let res = await settinglist()
    console.log(res);
    setin.current.setFieldsValue(res.data[0])
    // console.log(setin.current.setFieldsValue);
    setImageUrl(res.data[0].minibanner) //图片回显
  }


  useEffect(() => {
    getsettinglist()
  }, [])


  // 点击提交按钮的表单数据
  const [img, setimg]: any = useState() //图片重新赋值
  const onFinissh = async (values: any) => {
    console.log('数据:', values);
    let res = await settingedit({
      id: 1,
      formdata: {
        ...values, minibanner: img
      }
    })
    console.log(res);
  };

  // 微信小程序图片
  let Authorization: any = sessionStorage.getItem('token')
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>('');
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log(info.fileList[0].response);

    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      let url = info.fileList[0].response.data.src
      // console.log(url);
      setImageUrl(url)
      setimg(url)
    }
  };
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );


  // 下载二维码
  const downloadQRCode = () => {
    const canvas = document.getElementById('myqrcode')?.querySelector<HTMLCanvasElement>('canvas');
    if (canvas) {
      const url = canvas.toDataURL();
      const a = document.createElement('a');
      a.download = 'QRCode.png';
      a.href = url;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  };


  // 添加和返回按钮
  let [addButton, setButton]:any = useState(true) //取反
  let lick = () => {
    setButton(!addButton)
    console.log(addButton);
  }

  // 修改
  const [idd, setidd]: any = useState() //取反
  let modification = (e: any) => {
    return () => {
      // console.log(e);
      setidd(e)
      setButton(!addButton)
    }
  }

  // switch
  // let switchitem = async(e:any,is_null:any)=>{
  //   console.log(e,is_null);
  //   let {id} = is_null
  //   let res = await changestatus({
  //     id:1281,
  //     is_use:e
  //   })
  //   console.log(res);
  // }

  // 表头
  let columns: any = [
    {
      title: '核销人员姓名',
      dataIndex: 'fieldname',
      align: 'center',
      render: (fieldname: string) => <div>{fieldname}</div>
    },
    {
      title: '是否启用',
      dataIndex: 'is_null',
      align: 'center',
      render: (is_null: number, checkbox: any) => {
        if (is_null === 1) {
          return <div> <Switch defaultChecked className='Buttonnn' /></div> //onChange={(is_null)=>switchitem(is_null,checkbox)}
        } else {
          return <div> <Switch className='Buttonnn' /></div>
        }
      }
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      render: (id: string) => (
        <div><Button type="primary" className="upda" onClick={modification(id)}>修改</Button><Button type="primary" danger className="dele">删除</Button></div>
      )
    }
  ]
  // 表格左侧多选框
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  // 表格数据
  const [list, setlist] = useState()
  let listfield = async () => {
    let res = await field()
    console.log(res);
    setlist(res.data)

    setid({ //修改时要的id
      ...id, id: res.data[0].id
    })

    setname({ //修改时要的回显
      ...name,name: res.data[0].fieldname
    })
  }

  useEffect(() => {
    listfield()
  }, [])


  // 添加修改输入框
  const [xiu, setxiu] = useState({ fieldname: '' })
  let modiii = (e: any) => {
    setxiu({
      ...xiu, fieldname: e.target.value
    })
    setname({
      ...name, name: e.target.value
    })
  }

  //添加修改开关
  let [sw, setsw] = useState(0)
  const onChanges = (checked: any) => {
    // console.log(`switch to ${checked}`);
    if (checked === true) {
      checked = 1
    } else {
      checked = 2
    }
    setsw(
      sw = checked
    )
    // console.log(sw);
  };

  // 修改的回显
  const [name,setname] =useState({name:''})

  // 修改
  const [id, setid] = useState({ id: null }) //表格数据id
  let modi = async () => {
    let res:any = await addxiu(
      {
        id: id.id,
        formdata: {
          fieldname: xiu.fieldname,
          is_null: sw
        }
      }
    )
    if(res.code==='00000'){
      message.success('修改成功')
    }else{
      message.error('修改失败')
    }
  }

  // 添加
  let addAll = async() => {
    let res:any = await addxiu({
      formdata: {
        fieldname: xiu.fieldname,
        is_null: sw
      }
    })
    if(res.code==='00000'){
      message.success('添加成功')
      // setButton(addButton=false) //添加成功后返回页面
      // console.log(addButton);
      // listfield()
    }else{
      message.error('添加失败')
    }
  }



  return (<div className='system'>

    <Tabs defaultActiveKey="1" onChange={onChange} className="Tabs">

      {/* 网站设置 */}
      <TabPane tab='网站设置' key='1' className='website'>

        <Form
          ref={setin}
          onFinish={onFinissh} // button用submit 点击获取的数据
          autoComplete="off"
          initialValues={{
            sitename: 'aaa'

          }}
        >

          {/* 网站名称 */}
          <Form.Item
            label='网站名称' name="sitename" rules={[{ required: true, message: '请输入网站名称' }]}
          >
            <Input placeholder='网站名称' />
          </Form.Item>

          {/* 网站url */}
          <Form.Item
            label='网站url' name="url" rules={[{ required: true, message: '请输入网站url' }]}
          >
            <Input placeholder='网站url' />
          </Form.Item>

          {/* 关键字 */}
          <Form.Item
            label='关键字' name="keywords" rules={[{ required: true, message: '请输入关键字' }]}
          >
            <Input placeholder='关键字' />
          </Form.Item>

          {/* 简介 */}
          <Form.Item
            label='简介' name="desc" rules={[{ required: true, message: '请输入简介' }]}
          >
            <Input placeholder='简介' />
          </Form.Item>

          {/* 版权 */}
          <Form.Item
            label='版权' name="copyright" rules={[{ required: true, message: '请输入版权' }]}
          >
            <Input placeholder='版权' />
          </Form.Item>

          {/* 小程序ID */}
          <Form.Item
            label='小程序ID' name="miniappid" rules={[{ required: true, message: '请输入小程序ID' }]}
          >
            <Input placeholder='小程序ID' />
          </Form.Item>

          {/* 小程序密钥 */}
          <Form.Item
            label='小程序密钥' name="minisecret" rules={[{ required: true, message: '请输入小程序密钥' }]}
          >
            <Input placeholder='小程序密钥' />
          </Form.Item>

          {/* 公众号ID */}
          <Form.Item
            label='公众号ID' name="miniappid" rules={[{ required: true, message: '请输入公众号ID' }]}
          >
            <Input placeholder='公众号ID' />
          </Form.Item>

          {/* 公众号秘钥 */}
          <Form.Item
            label='公众号秘钥' name="appsecret" rules={[{ required: true, message: '请输入公众号秘钥' }]}
          >
            <Input placeholder='公众号秘钥' />
          </Form.Item>

          {/* 微信小程序图片 */}
          <Form.Item
            label="微信小程序图片" name="minibanner" rules={[{ required: true, message: '微信小程序图片' }]}
          >
            <Upload
              name="file"
              headers={{ Authorization }}
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://121.42.230.80/api/visit/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? < img src={imageUrl} alt="avatar" style={{ width: '100%', height: '100%' }} /> : uploadButton}
            </Upload>
          </Form.Item>

          {/* 提交 */}
          <Form.Item>
            <Button type="primary" htmlType="submit" className='buttonfff'>
              提交
            </Button>
          </Form.Item>

        </Form>

      </TabPane>

      {/* 离校二维码 */}
      <TabPane tab='离校二维码' key='2' className='lixiao'>
        <img src={img2} alt="二维码错误" className='imggg' />
        {/* <QRCode value='https://img1.imgtp.com/2023/02/14/gh398bv5.jpg' className='imggg' /> */}
        <div className='qrCode' onClick={downloadQRCode}>下载二维码</div>
      </TabPane>

      {/* Form表单设置 */}
      <TabPane tab='Form表单设置' key='3'>

        {/* 添加按钮 */}
        <div className='addButton'>
          {addButton ? <Button onClick={lick}>添加</Button> : <Button onClick={lick}>返回</Button>}
        </div>

        {/* 表格 */}
        <div>
          {
            addButton ? <Table
              columns={columns}//表头
              dataSource={list} //列表数据
              rowSelection={rowSelection}
              bordered={true}
              pagination={false}
              rowKey='id'
              className='tableee'
            />

              : <div className='addModification'> {/*添加修改*/}
                <Form>

                  {/* Form表单名 */}
                  <Form.Item
                    label="Form表单名"
                  >
                    <Input placeholder='Form表单名' value={xiu.fieldname===idd? '' :name.name} onChange={modiii} />
                  </Form.Item>

                  {/* Form表单名 */}
                  <Form.Item
                    label="是否开启" className='switchhf'
                  >
                    <Switch className='Buttonnn' onChange={onChanges}></Switch>
                  </Form.Item>

                  {
                    idd ?
                      <Button type='primary' onClick={modi}>修改</Button>
                      :
                      <Button type='primary' onClick={addAll}>添加</Button>
                  }

                </Form>
              </div>
          }
        </div>

      </TabPane>

    </Tabs>

  </div>);
}
export default system;